#include "ipc/cthreadmutex.h"

namespace PILO 
{
    namespace Core
    {
        namespace IPC 
        {

#           ifdef WINDOWS // windows version begins from here
            CThreadMutex::CThreadMutex()
            {
                InitializeCriticalSection(&_m_mutex);
            }
            CThreadMutex::~CThreadMutex()
            {
                DeleteCriticalSection(&_m_mutex);
            }
            BOOL CThreadMutex::tryLock() const
            {
                if(TryEnterCriticalSection(&_m_mutex)) {
                    return TRUE;
                }
                return FALSE;
            }
            void CThreadMutex::lock() const
            {
                EnterCriticalSection(&_m_mutex);
            }
            void CThreadMutex::unlock() const
            {
                LeaveCriticalSection(&_m_mutex);
            }


#           else
            CThreadMutex::CThreadMutex()
            {
                pthread_mutexattr_t attr;
                pthread_mutexattr_init(&attr);
                pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
                pthread_mutex_init(&_m_mutex, &attr);
            }
            CThreadMutex::~CThreadMutex()
            {
                pthread_mutex_destroy(&_m_mutex);
            }
            BOOL CThreadMutex::tryLock() const
            {
                if(0 == pthread_mutex_trylock(&_m_mutex)) {
                    return TRUE;
                }
                return FALSE;
            }
            void CThreadMutex::lock() const
            {
                pthread_mutex_lock(&_m_mutex);
            }

            void CThreadMutex::unlock() const
            {
                pthread_mutex_unlock(&_m_mutex);
            }


#           endif

        }

    }    
}
